# Create your views here.
import logging
from datetime import datetime

from rest_framework import filters, status
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters import rest_framework as django_filters
from utils.pagination import MyPageNumberPagination
from .models import ProductionIssues, IssueImage
from . import serializers

logger = logging.getLogger('dev07')


class ProductionIssuesFilter(django_filters.FilterSet):
    business_system = django_filters.CharFilter(field_name="business_system", lookup_expr="icontains")
    issue_description = django_filters.CharFilter(field_name="issue_description", lookup_expr="icontains")
    issue_category = django_filters.CharFilter(field_name="issue_category", lookup_expr="exact")
    impact_level = django_filters.CharFilter(field_name="impact_level", lookup_expr="exact")
    reporter = django_filters.CharFilter(field_name="reporter", lookup_expr="icontains")
    developer = django_filters.CharFilter(field_name="developer", lookup_expr="icontains")
    tester = django_filters.CharFilter(field_name="tester", lookup_expr="icontains")
    status = django_filters.CharFilter(field_name="status", lookup_expr="exact")
    create_time_start = django_filters.DateTimeFilter(field_name="create_time", lookup_expr="gte")
    create_time_end = django_filters.DateTimeFilter(field_name="create_time", lookup_expr="lte")

    class Meta:
        model = ProductionIssues
        fields = ["business_system", "issue_description", "issue_category", "impact_level", 
                  "reporter", "developer", "tester", "create_time", "status"]


class ProductionIssuesViewSet(viewsets.ModelViewSet):
    """
    list:
    获取生产问题列表

    retrieve:
    获取生产问题详情数据（包含图片信息）

    update:
    更新生产问题信息
    
    destroy:
    删除生产问题
    """
    queryset = ProductionIssues.objects.all()
    filter_backends = [django_filters.DjangoFilterBackend, filters.OrderingFilter]
    filterset_class = ProductionIssuesFilter
    ordering_fields = ['create_time', 'update_time']
    
    def get_serializer_class(self):
        """根据请求动作选择合适的序列化器"""
        if self.action == 'retrieve':
            # 查看详情时返回包含图片的完整信息
            return serializers.ProductionIssuesWithImagesModelSerializer
        return serializers.ProductionIssuesModelSerializer
    
    # 确保删除功能正常工作
    def destroy(self, request, *args, **kwargs):
        # 调用父类的destroy方法来执行实际的删除操作
        return super().destroy(request, *args, **kwargs)


class IssueImageViewSet(viewsets.ModelViewSet):
    """
    生产问题图片视图集
    
    list:
    获取生产问题图片列表

    create:
    上传生产问题图片

    destroy:
    删除生产问题图片
    """
    queryset = IssueImage.objects.all()
    serializer_class = serializers.IssueImageModelSerializer
    
    # 重写perform_create方法，支持独立上传和关联上传
    def perform_create(self, serializer):
        # 从URL中获取issue_id，如果不存在则为独立上传
        issue_id = self.kwargs.get('issue_pk')
        if issue_id:
            try:
                issue = ProductionIssues.objects.get(id=issue_id)
                serializer.save(issue=issue)
            except ProductionIssues.DoesNotExist:
                raise serializers.ValidationError("关联的生产问题不存在")
        else:
            # 独立上传，不关联任何生产问题
            serializer.save()
    
    # 过滤获取特定生产问题的图片，如果没有issue_id则返回所有图片
    def get_queryset(self):
        queryset = super().get_queryset()
        issue_id = self.kwargs.get('issue_pk')
        if issue_id:
            queryset = queryset.filter(issue_id=issue_id)
        return queryset